package com.dai.rpc.netty.handler;

import com.dai.rpc.netty.codec.MyRpcDecoder;
import com.dai.rpc.netty.codec.MyRpcEncoder;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.concurrent.DefaultEventExecutorGroup;

import java.util.concurrent.TimeUnit;

public class NettyServerInitiator extends ChannelInitializer<SocketChannel> {

    private DefaultEventExecutorGroup eventExecutors;

    public NettyServerInitiator(DefaultEventExecutorGroup eventExecutors) {
        this.eventExecutors = eventExecutors;
    }

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {

        // 添加心跳检测,10s没收到消息请求，就处理
        socketChannel.pipeline().addLast("heart",new IdleStateHandler(10, 0, 0, TimeUnit.SECONDS));

        // 添加编解码器
        socketChannel.pipeline().addLast("decoder",new MyRpcDecoder());
        socketChannel.pipeline().addLast("encoder",new MyRpcEncoder());
        // 添加消息处理器
        socketChannel.pipeline().addLast(eventExecutors,"messageHandler",new MyNettyServerHandler());
    }
}
